package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zhentao.dto.UserDto;
import com.zhentao.mapper.UserMapper;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.pojo.User;
import com.zhentao.service.UserService;
import com.zhentao.util.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Override
    public ResponseResult login(UserDto userDto) {
        if(!StringUtils.isBlank(userDto.getPassword()) || StringUtils.isBlank(userDto.getPhone())){
            ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        QueryWrapper<User> queryWrapper=new QueryWrapper();
        queryWrapper.lambda().eq(User::getPhone,userDto.getPhone());
        User user = userMapper.selectOne(queryWrapper);

        if(user==null){
            ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        String salt =user.getSalt();
        String paw = user.getPassword();
        String s = DigestUtils.md5DigestAsHex((userDto.getPassword() + salt).getBytes(StandardCharsets.UTF_8));
        if(!paw.equals(s)){
            ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
    Map<String,Object> map=new HashMap<>();
        String token = AppJwtUtil.getToken(user.getId().longValue());
        map.put("token",token);
        user.setPassword(null);
        user.setSalt(null);
        map.put("user",user);
        return ResponseResult.okResult(token);
    }

    @Override
    public ResponseResult add1(User user) {
        UUID uuid = UUID.randomUUID();
        String s = uuid.toString().replaceAll("-", "");
        String s1 = DigestUtils.md5DigestAsHex((user.getPassword() + s).getBytes(StandardCharsets.UTF_8));
        user.setPassword(s1);
         userMapper.insert(user);
        return ResponseResult.okResult("添加成功");
    }
}
